package tgipl3.medium.buildingBlocks;
import java.io.IOException;
import java.util.Arrays;
public class UserMainCode
{
	public static int[] output1;
	private static int output1Ind = 0, l, b;
	private static int[][] p, w;
	
	private static void change(int r, int c) {
		int min = p[r][c] + w[r][c];
		if(r <= 0 || r >= l - 1 || c <= 0 || c >= b - 1)
			min = 0;
		else if(p[r - 1][c] + w[r - 1][c] < min)
			min = p[r - 1][c] + w[r - 1][c];
		else if(p[r][c - 1] + w[r][c - 1] < min)
			min = p[r][c - 1] + w[r][c - 1];
		else if(p[r][c + 1] + w[r][c + 1] < min)
			min = p[r][c + 1] + w[r][c + 1];
		else if(p[r + 1][c] + w[r + 1][c] < min)
			min = p[r + 1][c] + w[r + 1][c];
		if(p[r][c] + w[r][c] > Math.max(min, p[r][c])) {
			w[r][c] = Math.max(min - p[r][c], 0);
			if(r > 0)
				change(r - 1, c);
			if(c > 0)
				change(r, c - 1);
			if(c < b - 1)
				change(r, c + 1);
			if(r < l - 1)
				change(r + 1, c);
		}
	}
	
	public static void GetWaterLevel(int input1,String input2)
	{
		input2 = input2.substring(1, input2.length() - 1);
		String tcs[] = input2.split("\\),\\(");
		output1 = new int[tcs.length];
		for(String tc : tcs) {
			int cind = tc.indexOf(',');
			l = Integer.parseInt(tc.substring(0, cind));
			tc = tc.substring(cind + 1);
			cind = tc.indexOf(',');
			b = Integer.parseInt(tc.substring(0, cind));
			tc = tc.substring(cind + 3, tc.length() - 2);
			p = new int[l][b];
			w = new int[l][b];
			String rows[] = tc.split("\\},\\{");
			int m = 0;
			for(int i = 0; i < l; i++) {
				String elts[] = rows[i].split(",");
				for(int j = 0; j < b; j++) {
					p[i][j] = Integer.parseInt(elts[j]);
					if(p[i][j] > m)
						m = p[i][j];
				}
			}
			for(int i = 0; i < l; i++)
				for(int j = 0; j < b; j++)
					w[i][j] = m - p[i][j];
			for(int j = 0; j < b; j++) {
				change(0, j);
				change(l - 1, j);
			}
			for(int i = 1; i < l - 1; i++) {
				change(i, 0);
				change(i, l - 1);
			}
			for(int i = 0; i < l; i++)
				for(int j = 0; j < b; j++)
					output1[output1Ind] += w[i][j];
			output1Ind++;
		}
	}
	
	public static void main(String[] args) throws IOException
	{
		String[] inputs = "1:(3,6,{{3,3,4,4,4,2},{3,1,3,2,1,4},{7,3,1,6,4,1}})".split(":");
		GetWaterLevel(Integer.parseInt(inputs[0]), inputs[1]);
		System.out.println(Arrays.toString(output1));
	}
}